package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import net.tsz.afinal.json.JsonMap;
import net.tsz.afinal.json.JsonParseHelper;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.*;
import so.shanku.essential.utils.LogUtil;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;

import java.util.*;

/**
 * Created by Jaelyn on 2015/8/17 0017.
 */
public class LoginActivity extends BaseUIActivity {
    @ViewInject(id = R.id.fill_view, click = "fill_view_click")
    private LinearLayout fill_view;
    /**
     * 第三方denglu
     */
    @ViewInject(id = R.id.third_login_layout)
    private LinearLayout third_login_layout;
    @ViewInject(id = R.id.login_qq_iv, click = "qqLogin")
    private TextView login_qq_iv;
    @ViewInject(id = R.id.login_wechat_iv, click = "weixinLogin")
    private TextView login_wechat_iv;
    @ViewInject(id = R.id.login_weibo_iv, click = "sinaLogin")
    private TextView login_weibo_iv;

    /**
     * 用户账户登录
     */
    @ViewInject(id = R.id.account_login_layout)
    private LinearLayout account_login_layout;
    @ViewInject(id = R.id.user_account_ed)
    private EditText user_account_ed;
    /**
     * 密码
     */
    @ViewInject(id = R.id.user_pwd_ed)
    private EditText user_pwd_ed;

    @ViewInject(id = R.id.forget_pwd_tv, click = "forget_pwd_tv_click")
    private TextView forget_pwd_tv;

    @ViewInject(id = R.id.login_login_bt, click = "login_login_bt_click")
    private TextView login_login_bt;
    private String userPhone;
    private String userPassword;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        setCenter_title(R.string.login);
        setBtn_menuText(R.string.register, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, RegisterActivity.class);
                startActivityForResult(intent, 1);
            }
        });
        addUnderLine(forget_pwd_tv);
        user_account_ed.setText(Utils.getUserPhone(this));
        mLoginController = MyApplication.getInstance().initThirdLogin(this);
    }

    /**
     * 空白处 结束
     *
     * @param view
     */
    public void fill_view_click(View view) {
        finish();
    }

    /**
     * 登录按钮
     */
    public void login_login_bt_click(View view) {
        if (userLoginJudge()) {
            getData_UserLogin();
        }
    }

    public void forget_pwd_tv_click(View view) {
        jumpTo(ForgetPasswordFirstActivity.class);
    }

    /**
     * 获取登录的接口
     */
    private void getData_UserLogin() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", userPhone);
        params.put("pwd", userPassword);
        params.put("tag", JPushInterface.getRegistrationID(this));

        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBack);
        queue.setActionName(GetDataConfing.GetAction_CheckLogin);
        queue.setWhat(GetDataConfing.what_CheckLogin);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    private UMSocialService mLoginController;
    // public static QQAuth mQQAuth;
    // private UserInfo mInfo;
    // private Tencent mTencent;


    //获取APPID及appkey，并且将APPID及appkey绑定在友盟主站后台， 同时注意在应用审核通过前必须添加测试账号，否则会出现110406报错。
    public void qqLogin(View view) {

        mLoginController.doOauthVerify(this, SHARE_MEDIA.QQ, thirdLoginListener);
        //thirdLoginToServer(1, "79F8044026D79F8E5CCBFF9C116417A3");  //test
    }

    public void sinaLogin(View view) {

        mLoginController.doOauthVerify(this, SHARE_MEDIA.SINA, thirdLoginListener);
        //thirdLoginToServer(2, "5548517447");  //test
    }

    public void weixinLogin(View view) {

        mLoginController.doOauthVerify(this, SHARE_MEDIA.WEIXIN, thirdLoginListener);
        //mLoginController.doOauthVerify(this, SHARE_MEDIA.WEIXIN, thirdLoginListener );
    }

    /**
     * 授权监听
     */
    SocializeListeners.UMAuthListener thirdLoginListener = new SocializeListeners.UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
        }

        @Override
        public void onError(SocializeException e, SHARE_MEDIA platform) {
            toast.showToast(R.string.authorize_third_login_error);
            Log.d(TAG, e.toString());
        }

        @Override
        public void onComplete(Bundle value, SHARE_MEDIA platform) {
            getThirdPlatforamInfo(platform);
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            toast.showToast(R.string.cancel_third_login);
        }
    };

    /**
     * 第三方登陆
     *
     * @param ordinal        平台
     * @param account        openId o
     * @param nickName       手机类型
     * @param thirdUserPhoto
     */
    private void thirdLoginToServer(int ordinal, String account, String nickName, String thirdUserPhoto) {
        loadingToast.show();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("typeId", ordinal);
        params.put("openId", account);
        params.put("tag", JPushInterface.getRegistrationID(this));
        params.put("nickName", nickName);// 1:android 2:ios
        params.put("userIcon", thirdUserPhoto);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_ThirdPlatformLogin);
        queue.setParamsNoJson(params);
        queue.setWhat(GetDataConfing.What_ThirdPlatformLogin);
        queue.setCallBack(callBack);
        getDataUtil.getData(queue);
    }

    public void getThirdPlatforamInfo(final SHARE_MEDIA platform) {
        //获取相关授权信息
        mLoginController.getPlatformInfo(mContext, platform, new SocializeListeners.UMDataListener() {
            @Override
            public void onStart() {
                toast.showToast(R.string.async_datas);
            }

            @Override
            public void onComplete(int status, Map<String, Object> info) {
                if (status == 200 && info != null) {
                    StringBuilder sb = new StringBuilder();
                    Set<String> keys = info.keySet();
                    for (String key : keys) {
                        sb.append(key + "=" + info.get(key).toString() + "\r\n");
                    }
                    LogUtil.d(TAG, sb.toString());
                    try {
                        if (platform == SHARE_MEDIA.QQ) {
                            String thirdNickName = info.get("screen_name").toString();
                            String thirdUserPhoto = info.get("profile_image_url").toString();
                            thirdLoginToServer(1, info.get("openid").toString(), thirdNickName, thirdUserPhoto);
                        } else if (platform == SHARE_MEDIA.SINA) {
                            String thirdNickName = info.get("screen_name").toString();
                            String thirdUserPhoto = info.get("profile_image_url").toString();
                            thirdLoginToServer(2, info.get("uid").toString(), thirdNickName, thirdUserPhoto);
                        } else {
                            String thirdNickName = info.get("nickname").toString();
                            String thirdUserPhoto = info.get("headimgurl").toString();
                            thirdLoginToServer(3, info.get("openid").toString(), thirdNickName, thirdUserPhoto);
                        }
                    } catch (Exception e) {
                        toast.showToast("发生错误：" + e.toString());
                    }

                } else {
                    toast.showToast("发生错误：" + status);
                }

            }
        });
    }

    private IGetServicesDataCallBack callBack = new IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetDataQueue entity) {
            loadingToast.dismiss();
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext,
                        entity.getInfo())) {
                    LogUtil.d(TAG, entity.getInfo());
                    if (entity.what == GetDataConfing.what_CheckLogin || entity.what == GetDataConfing.What_ThirdPlatformLogin) {
                        toast.showToast(R.string.login_success);
                        JsonMap<String, Object> dataInfo = JsonParseHelper.getJsonMap_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        //Utils.saveUserLoginStyle(mContext, false);
                        Utils.saveUserInfos(mContext, dataInfo);
                        //获取服务器端存储的数据
                        finish();
                        //jumpTo(MainActivity.class, true);

                    }
                }
            } else {
                ShowGetDataError.showNetError(mContext);
            }

        }
    };


    public boolean judgeMobileNo() {
        boolean isjudge = true;
        userPhone = user_account_ed.getText().toString();
        if (userPhone == null || "".equals(userPhone)) {
            toast.showToast(R.string.register_name_null);
            isjudge = false;
        } else if (userPhone.length() < 11) {
            toast.showToast(R.string.phone_formal_error);
            isjudge = false;
        }
        return isjudge;
    }

    /**
     * 密码判断
     */
    public boolean isPasswordAuthentication(String password) {
        if (!StringUtil.passwordAuthenticationLength(password)) {
            toast.showToast(R.string.register_passwordRule);
            return false;
        } else if (!StringUtil.passwordAuthentication(password)) {
            toast.showToast(R.string.password_format_error);
            return false;
        }
        return true;
    }

    /**
     * 登录判断
     */
    public boolean userLoginJudge() {
        userPassword = user_pwd_ed.getText().toString();
        if (userPassword == null || "".equals(userPassword)) {
            toast.showToast(R.string.register_password_null);
            return false;
        } else {
            if (isPasswordAuthentication(userPassword)) {
                return judgeMobileNo();
            } else {
                return false;
            }
        }
    }

    /**
     * 当 SSO 授权 Activity 退出时，该函数被调用。
     *
     * @see {@link android.app.Activity#onActivityResult}
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */
        UMSsoHandler ssoHandler = mLoginController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                finish();
            }
        }
    }
}